﻿#系统类包
import os
import shutil
import SimpleITK as sitk
import numpy as np
import json
import uuid
from util import log

class Mask2Nii(object):
    def __init__(self):
        self.endpath = os.getcwd()
        self.log = log.lgtest()
        self.log_name = 'Mask2Nii'
    def process(self,data):
        try:
            request_uuid = str(uuid.uuid4())
            self.log.lognow(request_uuid + '-----> Mask2Nii.process request: ' + str(data), 'info', self.log_name)

            rows = data['rows']
            columns = data['columns']
            maxInstanceNumber = data['maxInstanceNumber']
            destPath = data['destPath']
            coordFileParentPath = data['coordFileParentPath']
            nii_parent_out_path = os.path.join(destPath, 'mask')
            nii_out_path = os.path.join(nii_parent_out_path, '1.nii.gz')

            os.makedirs(nii_parent_out_path, exist_ok=True)

            np_array = np.zeros((int(maxInstanceNumber), int(columns), int(rows)), dtype=np.uint8)
            for file in os.listdir(coordFileParentPath):
                number = os.path.splitext(file)[0]
                with open(os.path.join(coordFileParentPath, file), 'r') as f:
                    coord_arr = json.load(f)
                    for coord in coord_arr:
                        y = int(coord) // columns
                        x = int(coord) % columns
                        np_array[int(number), int(y), int(x)] = 1

            # np_array = np.flip(np_array, axis=0)

            itkImage = sitk.GetImageFromArray(np_array)
            itkWriter = sitk.ImageFileWriter()
            itkWriter.SetFileName(nii_out_path)
            itkWriter.SetUseCompression(True)
            itkWriter.Execute(itkImage)

            self.log.lognow(request_uuid + '-----> Mask2Nii.process response: success', 'info', self.log_name)

            return {"msg": "", "data": {"niiPath": nii_out_path}, "code": 0}
        except Exception as e:
            self.log.lognow('Mask2Nii fail ' + str(e), 'error', self.log_name)
            return {"msg": "Mask2Nii fail", "data": {}, "code": 1}





        
        
